package com.blog.blog.controller;

import com.blog.blog.common.ApiBaseResponse;
import com.blog.blog.service.CaptchaService;
import com.blog.blog.util.annotations.RateLimit;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/api/captcha")
public class CaptchaController {

	private final CaptchaService captchaService;

	public CaptchaController(CaptchaService captchaService) {
		this.captchaService = captchaService;
	}

	@GetMapping("/qa")
	@RateLimit(key = "captcha:qa", rate = 30, interval = 60)
	public ApiBaseResponse<Map<String, Object>> generate() {
		return ApiBaseResponse.success(captchaService.generateQA(120));
	}

	@PostMapping("/verify")
	public ApiBaseResponse<Boolean> verify(@RequestBody Map<String, String> body) {
		String token = body.get("token");
		String answer = body.get("answer");
		boolean ok = captchaService.validate(token, answer, true);
		return ok ? ApiBaseResponse.success(true) : ApiBaseResponse.error(400, "验证码错误或已过期");
	}
}


